import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/utils/api'

export interface User {
  id: number
  username: string
  email: string
  phone?: string
  avatar?: string
  is_active: boolean
  date_joined: string
  roles: Array<{
    id: number
    name: string
    code: string
  }>
  permissions: Array<{
    id: number
    name: string
    code: string
  }>
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string>(localStorage.getItem('access_token') || '')
  const refreshToken = ref<string>(localStorage.getItem('refresh_token') || '')
  const user = ref<User | null>(null)

  const isAuthenticated = computed(() => !!token.value)

  // 登录
  const login = async (username: string, password: string) => {
    try {
      const response = await api.post('/auth/login/', {
        username,
        password
      })

      if (response.data.success) {
        const { access_token, refresh_token, user: userData } = response.data.data
        
        token.value = access_token
        refreshToken.value = refresh_token
        user.value = userData

        localStorage.setItem('access_token', access_token)
        localStorage.setItem('refresh_token', refresh_token)

        return { success: true }
      } else {
        return { success: false, message: response.data.message }
      }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.response?.data?.message || '登录失败' 
      }
    }
  }

  // 注册
  const register = async (userData: {
    username: string
    email: string
    password: string
    password_confirm: string
    phone?: string
  }) => {
    try {
      const response = await api.post('/auth/register/', userData)
      
      if (response.data.success) {
        return { success: true, message: response.data.message }
      } else {
        return { success: false, message: response.data.message }
      }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.response?.data?.message || '注册失败' 
      }
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (refreshToken.value) {
        await api.post('/auth/logout/', {
          refresh_token: refreshToken.value
        })
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      token.value = ''
      refreshToken.value = ''
      user.value = null
      
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await api.get('/auth/user-info/')
      if (response.data.success) {
        user.value = response.data.data
        return true
      }
      return false
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return false
    }
  }

  // 检查权限
  const hasPermission = (permissionCode: string) => {
    if (!user.value) return false
    return user.value.permissions.some(p => p.code === permissionCode)
  }

  // 检查角色
  const hasRole = (roleCode: string) => {
    if (!user.value) return false
    return user.value.roles.some(r => r.code === roleCode)
  }

  return {
    token,
    refreshToken,
    user,
    isAuthenticated,
    login,
    register,
    logout,
    fetchUserInfo,
    hasPermission,
    hasRole
  }
})
